﻿using System.IO;
using System.Linq;
using ClosedXML.Excel;
using Haimen.Excel;

namespace Haimen;

internal class GroupConfigReader(ExcelFileUtils excelUtil) {

  public DataGroupCfg[] Read(string path) {
    using FileStream stream = _excelUtil.OpenRead(path);
    using XLWorkbook resultBook = new(stream);

    return resultBook.Worksheets
      .Select(MakeGroupCfg)
      .ToArray();
  }

  DataGroupCfg MakeGroupCfg(IXLWorksheet sheet) {
    IXLRow headerRow = sheet.Row(1);
    int lastCol = headerRow.LastCellUsed(XLCellsUsedOptions.All)
      .WorksheetColumn()
      .ColumnNumber();

    DataHeaderCfg[] headerList = Enumerable.Range(1, lastCol)
      .Select(c => headerRow.Cell(c))
      .Select(c => MakeHeaderCfg(c.GetText()))
      .ToArray();

    return new(sheet.Name, headerList);
  }

  DataHeaderCfg MakeHeaderCfg(string configStr) {
    string[] configSplit = configStr.Split('_');
    string name = configSplit[0];
    if (configSplit.Length == 1) {
      return new(name, HeaderColFunc.KEY);
    }

    HeaderColFunc func = configSplit[1] switch {
      "sum" => HeaderColFunc.SUM,
      "count" => HeaderColFunc.COUNT,
      _ => HeaderColFunc.VLOOKUP,
    };

    return new(name, func);
  }

  readonly ExcelFileUtils _excelUtil = excelUtil;
}

internal enum HeaderColFunc { KEY, SUM, VLOOKUP, COUNT }
internal record DataHeaderCfg(string Name, HeaderColFunc Func);
internal record DataGroupCfg(string Name, DataHeaderCfg[] Header);
